#include "ordermanagementpanel.h"
#include <QTableWidget>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QMessageBox> // For placeholders
#include <QComboBox>
#include <QLineEdit>
#include <QDateEdit>
#include <QFormLayout> // For filter layout
#include <QFont>       // For setting font
#include <QCalendarWidget> // For accessing calendar widget
#include <QLocale>     // Include for QLocale
#include <QCalendarWidget> // For accessing calendar widget
#include <QDate> // For QDate::currentDate()
#include <QDateTime> // For time_t conversion

// Include C backend header for orders
extern "C" {
#include "../backend/order.h"
}

OrderManagementPanel::OrderManagementPanel(QWidget *parent)
    : QWidget(parent)
{
    setupUi();
    loadOrders(); // Load orders initially
}

OrderManagementPanel::~OrderManagementPanel()
{
    freeOrderList();
}

void OrderManagementPanel::setupUi()
{
    // Filter Controls (Example)
    comboFilterType = new QComboBox();
    comboFilterType->addItem("按用户查询", "user");
    comboFilterType->addItem("按商品查询", "product");
    comboFilterType->addItem("按日期范围查询", "date");
    // Add more filters as needed (e.g., status)

    editFilterValue = new QLineEdit(); // For user/product name/ID
    editFilterValue->setPlaceholderText("输入查询值...");

    dateStart = new QDateEdit(QDate::currentDate().addMonths(-1)); // Default to last month
    dateStart->setCalendarPopup(true);
    dateEnd = new QDateEdit(QDate::currentDate());
    dateEnd->setCalendarPopup(true);
     // Explicitly set display format to avoid locale issues
     const QString dateFormat = "yyyy-MM-dd";
     dateStart->setDisplayFormat(dateFormat);
     dateEnd->setDisplayFormat(dateFormat);

    // Set font for DateEdit and its calendar popup to ensure Chinese characters display correctly
    QFont calendarFont("Microsoft YaHei UI", 10); // Font for the popup calendar
    QFont dateEditFont("Segoe UI", 10); // Try a different font for the line edit part
    dateStart->setFont(dateEditFont);
    dateEnd->setFont(dateEditFont);
    // Set font AND locale for the popup calendar
    dateStart->calendarWidget()->setFont(calendarFont);
    dateStart->calendarWidget()->setLocale(QLocale(QLocale::Chinese, QLocale::China));
    dateEnd->calendarWidget()->setFont(calendarFont);
    dateEnd->calendarWidget()->setLocale(QLocale(QLocale::Chinese, QLocale::China));

    btnApplyFilter = new QPushButton("🔍 应用筛选");

    QWidget* filterWidget = new QWidget();
    QFormLayout* filterLayout = new QFormLayout(filterWidget);
    filterLayout->addRow("筛选类型:", comboFilterType);
    filterLayout->addRow("查询值:", editFilterValue);
    filterLayout->addRow("开始日期:", dateStart);
    filterLayout->addRow("结束日期:", dateEnd);
    filterLayout->addRow(btnApplyFilter);
    filterLayout->setContentsMargins(0,0,0,0);


    // Table View for Orders
    orderTable = new QTableWidget();
    // Define columns based on Order struct in backend/order.h
    // Example: ID, UserID, DrinkID, Quantity, TotalPrice, OrderTime, Status
    orderTable->setColumnCount(7);
    orderTable->setHorizontalHeaderLabels(QStringList() << "订单ID" << "用户ID" << "饮品ID" << "数量" << "总价" << "下单时间" << "状态");
    orderTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    orderTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    orderTable->setSelectionMode(QAbstractItemView::SingleSelection);
    orderTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // Buttons
    btnViewDetails = new QPushButton("👁️ 查看详情"); // Or "✏️ 修改状态"
    btnDelete = new QPushButton("❌ 删除订单");
    btnRefresh = new QPushButton("🔄 刷新列表");

    // Order Count Label
    lblOrderCount = new QLabel("总订单数：0");

    // Layouts
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(btnViewDetails);
    buttonLayout->addWidget(btnDelete);
    buttonLayout->addStretch();
    buttonLayout->addWidget(btnRefresh);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(filterWidget); // Add filter section
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(orderTable);
    mainLayout->addWidget(lblOrderCount, 0, Qt::AlignRight);

    // Connections
    connect(btnRefresh, &QPushButton::clicked, this, &OrderManagementPanel::loadOrders);
    connect(btnViewDetails, &QPushButton::clicked, this, &OrderManagementPanel::viewOrderDetails);
    connect(btnDelete, &QPushButton::clicked, this, &OrderManagementPanel::deleteOrder);
    connect(btnApplyFilter, &QPushButton::clicked, this, &OrderManagementPanel::applyFilters);
    connect(orderTable, &QTableWidget::itemDoubleClicked, this, &OrderManagementPanel::viewOrderDetails);
}

void OrderManagementPanel::loadOrders()
{
    freeOrderList();
    // Assuming orders are stored in "data/orders.dat"
    int count = load_orders("orders.dat", &orderListHead); // Pass only filename
    lblOrderCount->setText(QString("总订单数：%1").arg(count));
    populateTable();
    // QMessageBox::information(this, "提示", "订单加载功能（开发中）"); // Remove placeholder
}

void OrderManagementPanel::populateTable()
{
    clearTable();
    OrderNode* current = orderListHead;
    int row = 0;
    while (current != nullptr) {
        orderTable->insertRow(row);
        orderTable->setItem(row, 0, new QTableWidgetItem(QString::number(current->data.id)));
        orderTable->setItem(row, 1, new QTableWidgetItem(QString::number(current->data.user_id))); // Consider showing username instead?
        orderTable->setItem(row, 2, new QTableWidgetItem(QString::number(current->data.drink_id))); // Consider showing drink name instead?
        orderTable->setItem(row, 3, new QTableWidgetItem(QString::number(current->data.quantity)));

        // Calculate total price (assuming price is stored elsewhere or needs lookup)
        // For now, let's assume Order struct might have total_price later, or we skip it
        // orderTable->setItem(row, 4, new QTableWidgetItem(QString::number(current->data.total_price, 'f', 2)));
        orderTable->setItem(row, 4, new QTableWidgetItem("N/A")); // Placeholder for total price

        // Convert time_t to QString
        QDateTime dt = QDateTime::fromSecsSinceEpoch(current->data.order_time);
        orderTable->setItem(row, 5, new QTableWidgetItem(dt.toString("yyyy-MM-dd hh:mm:ss")));

        // Convert status code to text
        QString statusText;
        switch (current->data.status) {
            case ORDER_STATUS_PENDING: statusText = "待处理"; break;
            case ORDER_STATUS_FINISHED: statusText = "已完成"; break;
            case ORDER_STATUS_CANCELED: statusText = "已取消"; break;
            default: statusText = "未知"; break;
        }
        orderTable->setItem(row, 6, new QTableWidgetItem(statusText));

        // Store order ID in the first column's item data
        orderTable->item(row, 0)->setData(Qt::UserRole, current->data.id);

        current = current->next;
        row++;
    }
}

void OrderManagementPanel::clearTable()
{
    orderTable->clearContents();
    orderTable->setRowCount(0);
}

void OrderManagementPanel::freeOrderList()
{
    if (orderListHead) {
        free_all_orders(orderListHead);
        orderListHead = nullptr;
    }
}

void OrderManagementPanel::viewOrderDetails()
{
    // TODO: Implement view order details logic (maybe a dialog)
    QMessageBox::information(this, "提示", "查看订单详情功能（开发中）");
}

void OrderManagementPanel::deleteOrder()
{
    // TODO: Implement delete order confirmation and logic
    QMessageBox::information(this, "提示", "删除订单功能（开发中）");
    // After deleting, call loadOrders()
}

void OrderManagementPanel::applyFilters()
{
     // TODO: Implement filtering logic based on selected criteria
     QMessageBox::information(this, "提示", "筛选订单功能（开发中）");
     // Call loadOrders() or populateTable() with filtered data
     loadOrders(); // For now, just reload all
}